<?php

namespace app\common\helpers;

class ServiceTimeHelper
{
    /**
     * 获取指定年份的开始结束时间
     * @param $year
     * @param bool $isFormat
     * @param string $format
     * @return array
     */
    public function year($year, $isFormat = true, $format = 'Y-m-d')
    {
        $start = date('Y-01-01 00:00:00', strtotime($year.'-01'));
        $nextYear = strtotime('+ 1 year', strtotime($start));
        $end = date('Y-m-d 23:59:59', strtotime('- 1 day', $nextYear));
        if ($isFormat) {
            return self::formatStartAndEnd([$start, $end], $format);
        }
        return [$start, $end];
    }

    public static function getStartAndEnd($type, $isFormat = false, $format = 'Y-m-d')
    {
        switch ($type) {
            // 本年
            case 'y':
                $start = date('Y-1');
                $end = date('Y-1');
                $type = 'year';
                break;
            // 本月
            case 'm':
                $start = date('Y-m');
                $end = date('Y-m');
                $type = 'month';
                break;
            // 近半年
            case 'nhy':
                $start = date('Y-m', strtotime('- 5 month'));
                $end = date('Y-m');
                $type = 'day';
                break;
            // 近30天
            case 'nm':
                $start = date('Y-m-d', strtotime('- 29 day'));
                $end = date('Y-m-d');
                $type = 'day';
                break;
            // 近7天
            case 'nw':
                $start = date('Y-m-d', strtotime('- 6 day'));
                $end = date('Y-m-d');
                $type = 'day';
                break;
            // 本日
            case 'c':
            default:
                $start = date('Y-m-d');
                $end = date('Y-m-d');
                $type = 'day';
                break;
        }
        if ($isFormat) {
            list($start, $end) = CommonHelper::getStartAndEnd($start, $end, $type);
            return self::formatStartAndEnd([$start, $end], $format);
        }
        return CommonHelper::getStartAndEnd($start, $end, $type);
    }

    public static function formatStartAndEnd($startAndEnd, $format = 'Y-m-d')
    {
        return array_map(function ($item) use ($format) {
            return date($format, strtotime($item));
        }, $startAndEnd);
    }
}